/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dw2;

import javax.sound.midi.*;
import java.io.*;
/**
 *
 * @author Chad Bonivtch
 */
public abstract class MusicPlayer {

    protected File file;
    protected Sequencer sequencer;
    protected Synthesizer synthesizer;
    protected float factor;

    public abstract void setFile(String filename);

    public void resume(long position)
    {
        play(position,1);
    }

    public void play()
    {
        play(0,1);
    }
    public void play(long position, int rep)
    {

        try
        {


            Sequence sequence = MidiSystem.getSequence((file));

            sequencer = MidiSystem.getSequencer(false);
            sequencer.open();

            sequencer.setSequence(sequence);

            synthesizer = MidiSystem.getSynthesizer();
            synthesizer.open();
            Receiver synthReceiver = synthesizer.getReceiver();
            Transmitter seqTransmitter = sequencer.getTransmitter();
            seqTransmitter.setReceiver(synthReceiver);

            sequencer.start();
            sequencer.addMetaEventListener(
                new MetaEventListener() {
                    public void meta(MetaMessage event) {
                        if(event.getType() == 47) {
                            sequencer.close();
                            synthesizer.close();
                        }
                    }
                }
            );
            if(rep == 1) {
                sequencer.setLoopStartPoint(1);
                sequencer.setLoopEndPoint(-1);
                sequencer.setLoopCount(Sequencer.LOOP_CONTINUOUSLY);

                sequencer.setTickPosition(position);
                sequencer.start();
            }
        }
        catch(MidiUnavailableException e) {}
        catch(InvalidMidiDataException e) {}
        catch(IOException e) {}
    }

    public long pause() {
        long tick_pos = sequencer.getTickPosition();
        stop();
        return tick_pos;

    }
    public void stop() {

        sequencer.stop();
        sequencer.close();
        synthesizer.close();
    }

    public float getTempo() {
        factor = sequencer.getTempoFactor();
        return factor;
    }

    public void setDanger(double factor) {
        sequencer.setTempoFactor((float)factor);
    }

    public void setNormal() {
        sequencer.setTempoFactor((float)1.0);
    }
}
